﻿using Itech_Run.Application.Contracts.Shared.Dto;
using Itech_Run.Application.Shared;
using Itech_Run.Blog.Application.Contracts.Dto;
using Itech_Run.Blog.Application.Contracts.Service;
using Itech_Run.Blog.Domain.Entity;
using Volo.Abp.Domain.Repositories;

namespace Itech_Run.Blog.Application.Service
{
    public class BlogPersonLabelService : BaseApplicationService<Blog_PersonLabel>, IBlogPersonLabelService
    {
        private readonly IRepository<Blog_PersonLabel, string> _blogPersonLabelRepository;
        private readonly IRepository<Blog_PersonLabel_Map, string> _blogPersonLabelMapRepository;
        public BlogPersonLabelService(IRepository<Blog_PersonLabel, string> blogPersonLabelRepository, IRepository<Blog_PersonLabel_Map, string> blogPersonLabelMapRepository)
        {
            _blogPersonLabelRepository = blogPersonLabelRepository;
            _blogPersonLabelMapRepository = blogPersonLabelMapRepository;
        }
        public async Task<List<KeyValueDto>> GetListAsync(string operateUser)
        {
            var query =
                from r in await _blogPersonLabelRepository.GetQueryableAsync()
                where r.UserId == operateUser
                orderby r.Name ascending
                select new KeyValueDto
                {
                    Key = r.Id,
                    Value = r.Name
                };

            return query.ToList();
        }

        public async Task<BlogPersonLabelHotDto> GetHotListAsync(string operateUser)
        {
            var query =
                from l in await _blogPersonLabelRepository.GetQueryableAsync()
                join lm in (await _blogPersonLabelMapRepository.GetQueryableAsync()).Where(p => p.Blog.IsPublish == true) on l.Id equals lm.PersonLabelId
                into lr
                from lr1 in lr.DefaultIfEmpty()
                where l.UserId == operateUser
                group l by new { l.Id, l.Name } into g
                select new BlogPersonLabelHotItemDto
                {
                    Id = g.Key.Id,
                    Name = g.Key.Name,
                    Count = g.Count()
                };
            var items = query.ToList();
            BlogPersonLabelHotDto finalResult = new BlogPersonLabelHotDto
            {
                Items = items,
                MinCount = items.Min(s => s.Count),
                MaxCount = items.Max(s => s.Count)
            };
            return finalResult;
        }
    }
}
